﻿namespace Oddo.Concept.Crm.Common.Presentation.ViewModels
{
    using System.Windows.Input;
    using Microsoft.Practices.Prism.Commands;
    using Microsoft.Practices.Unity;
    using Oddo.Concept.Crm.Common.Security;
    using Oddo.Concept.Crm.Common.ViewModels;

    public interface IAuthenticationView
    {
        bool? DialogResult { get; set; }
        void Close();
    }

    public class AuthenticationViewModel : ViewModelBase
    {
        private ICommand _validateCommand;
        private ICommand _cancelCommand;

        /// <summary>
        /// Obtient la commande a executer pour valider l'authtification
        /// </summary>
        public ICommand ValidateCommand
        {
            get { return _validateCommand ?? (_validateCommand = new DelegateCommand(ValidateCommandHandler)); }
        }
        /// <summary>
        /// Obtient la commande a executer pour annuler l'authentification
        /// </summary>
        public ICommand CancelCommand
        {
            get { return _cancelCommand ?? (_cancelCommand = new DelegateCommand(CancelCommandHandler)); }
        }
        /// <summary>
        /// Obtient ou définit le nom de l'utilisateur
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// Obtient ou définit le mot de passe de l'utilisateur
        /// </summary>
        public string Password { get; set; }

        private void ValidateCommandHandler()
        {
            bool isValid = ValidateUser();
            var view = Container.Resolve<IAuthenticationView>();
            view.DialogResult = isValid;
            view.Close();
        }

        private void CancelCommandHandler()
        {
            var view = Container.Resolve<IAuthenticationView>();
            view.DialogResult = false;
            view.Close();
        }

        private bool ValidateUser()
        {
            var svc = Container.Resolve<IAuthenticationService>();
            svc.ValidateCredentials(UserName,Password);
            Password = null;
            UserName = null;
            return svc.IsAuthenticated;
        }
    }
}